'use strict';

angular.module('afasApp')
  .controller('InvoicesCtrl', ['$scope', '$rootScope', 'Services', '$stateParams', '$state', '$filter', '$modal', '$locale', '_', function ($scope, $rootScope, Services, $stateParams, $state, $filter, $modal, $locale, _) {
    // console.log($filter);

    $scope.viewInvoice = true;
    $scope.paymentNew = [];
    $scope.paymentNew.payments = [];
    $scope.paymentNew.StudentId = $stateParams.id;
    $scope.invoices = [];
    Services.setSelectedInvoice([]);
    $scope.selectedInvoice = Services.getSelectedInvoice();
    $scope.Disc = {};
    $scope.Disc.params = {
      'getall': true,
      'include': 'discount_type,invoice'
    };
    $scope.errors = {};
    $scope.psDiscounts = false;

    $scope.params = {
      'include'     : 'all,student,payment,student_discounts',
      'paid'        : false,
      'invoice_type': '',
      'student_name': '',
      'order_by': 'UpdatedAt',
      'order_type': 'DESC'
    };

    $scope.payInvoice = function(){
      Services.setSelectedInvoice($scope.selectedInvoice);
      $state.go('^.new');
    }

    $scope.searchInvoices = function() {
      getResultsPage($scope.pagination.current);
    }

    $scope.checkSelected = function(Id) {
      return _.where($scope.selectedInvoice, { Id: Id }).length > 0;
    }

    // PAGINATION
    $scope.pagesize = 10;

    $scope.pagination = {
        current: 1
    };

    $scope.pageChanged = function(newPage) {
      console.log("invoice");
      getResultsPage(newPage);
    };

    function getResultsPage(pageNumber) {
      var data = $scope.params;
      data.pagesize = $scope.pagesize;
      data.page = (pageNumber - 1);
      $scope.pagination.current = pageNumber;
      Services.getItems('invoices', data)
      .then(function( results ) {
        var pagingData = angular.fromJson(results.headers['x-pagination']);
        $scope.totalItems = pagingData.TotalCount;
        $scope.invoices = results.data;
      });
    }
    getResultsPage(1);

    $scope.orderUnpaid = function(type) {
      $scope.params.order_type = type;
      getResultsPage(1);
    }

    $scope.toggleSelection = function(invoice) {
      var items = _.where($scope.selectedInvoice, {Id: invoice.Id});
      var item = _.findWhere($scope.selectedInvoice, {Id: invoice.Id});

      if (items.length > 0) {
        $scope.selectedInvoice = _.without($scope.selectedInvoice, item);
      } else {
        $scope.selectedInvoice.push(invoice);
      }
    };

    // PAGINATION
    // $scope.pagesize = 5;

    // $scope.Disc.pagination = {
    //   current: 1
    // };

    // $scope.pageChangedDisc = function(newPage) {
    //   console.log("discount");
    //   getResultsPageDisc(newPage);
    // };

    // function getResultsPageDisc(pageNumber) {
    function getResultsPageDisc() {
      var data = $scope.Disc.params;
      // data.pagesize = 10;
      // data.page = (pageNumber - 1);
      // $scope.Disc.pagination.current = pageNumber;
      Services.getItems('student_discounts', data)
      .then(function( results ) {
        // var pagingData = angular.fromJson(results.headers['x-pagination']);
        // $scope.Disc.totalItems = pagingData.TotalCount;
        $scope.discounts = results.data;
      });
    };

    $scope.manageDiscount = function(invoice){
      $scope.psDiscounts = true;
      $scope.InvoiceChosen = invoice;
      // Services.getItem('invoices', invoice.Id, {'include': 'student,payment,student_discounts'})
      // .then(function(results){
      //   $scope.InvoiceChosen = results.data;
        if ($scope.InvoiceChosen.PlacementTest) {
          $scope.Disc.params.student = $scope.InvoiceChosen.PlacementTest.Student.Id;
          $scope.Disc.params.studentName = $scope.InvoiceChosen.PlacementTest.Student.FullName;
        };
        if ($scope.InvoiceChosen.Enrollment) {
          $scope.Disc.params.student = $scope.InvoiceChosen.Enrollment.Student.Id;
          $scope.Disc.params.studentName = $scope.InvoiceChosen.Enrollment.Student.FullName;
        };
        if ($scope.InvoiceChosen.MakeUpTest) {
          $scope.Disc.params.student = $scope.InvoiceChosen.MakeUpTest.Student.Id;
          $scope.Disc.params.studentName = $scope.InvoiceChosen.MakeUpTest.Student.FullName;
        };
        // getResultsPageDisc(1);
        getResultsPageDisc();
      // });
    };

    $scope.checkSelected = function(Id) {
      if ($scope.InvoiceChosen) {
        return _.where($scope.InvoiceChosen.StudentDiscounts, { Id: Id }).length > 0;
      };
    };

    $scope.toggleDiscount = function(discount) {
      console.log(discount);
      var items = _.where($scope.InvoiceChosen.StudentDiscounts, {Id: discount.Id});
      var item = _.findWhere($scope.InvoiceChosen.StudentDiscounts, {Id: discount.Id});

      if (items.length > 0) {
        $scope.InvoiceChosen.StudentDiscounts = _.without($scope.InvoiceChosen.StudentDiscounts, item);
      } else {
        $scope.InvoiceChosen.StudentDiscounts.push(discount);
      }
    };

    $scope.submitDiscount = function(){
      var TotalDisc = 0;
      angular.forEach($scope.InvoiceChosen.StudentDiscounts, function(newValue, oldValue){
        if (!newValue.Percentage) {
          newValue.Percentage = 0;
        };
        if (!newValue.Amount) {
          newValue.Amount = 0;
        };
        var disc = Math.abs(($scope.InvoiceChosen.TotalAmount*(newValue.Percentage/100))+newValue.Amount);
        TotalDisc = TotalDisc + disc;
      });
      $scope.InvoiceChosen.TotalDiscount = TotalDisc;

      var data = angular.copy($scope.InvoiceChosen);

      delete data.Enrollment;
      delete data.PlacementTest;
      delete data.TotalDiscount;
      delete data.MakeUpTest;
      Services.update('invoices', data, data.Id)
      .then(function(results){
        $scope.psDiscounts = false;
      }, function (results) {
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      })
    };

    $scope.getLabelFilter = function(array, value) {
      var data = _.findWhere(array, {'Query': value});
      return data.Label;
    };

    $scope.getLabelOrder = function(value) {
      var data = [
        {
          'Query': 'DESC',
          'Label': 'Newest First'
        },
        {
          'Query': 'ASC',
          'Label': 'Latest First'
        }
      ];
      data = _.findWhere(data, {'Query': value});
      return data.Label;
    };
  }])
  .controller('InvoiceNewCtrl', ['$scope', 'Services', '$filter', '$state', '$stateParams', '_', '$modal', function ($scope, Services, $filter, $state, $stateParams, _, $modal) {

    $scope.selectedInvoice = Services.getSelectedInvoice();
    $scope.newPayment = {
      'Client': {},
      'PaymentStatus': 0
    };
    $scope.postedPayment = {};
    $scope.clients = [];
    $scope.errors = {};
    $scope.Disc = {};
    $scope.Disc.params = {
      'include': 'discount_type,invoice'
    };
    $scope.psDiscounts = false;

    $scope.Statuses = [
      {
        'Id': 0,
        'Label': 'Direct'
      },
      {
        'Id': 2,
        'Label': 'By Invoice'
      }
    ];

    // CLIENTS
    $scope.params = {
    };
    $scope.pagesize = 6;

    $scope.pagination = {
      current: 1
    };
    $scope.InvoiceChosen = {};

    $scope.pageChanged = function(newPage) {
      getResultsPage(newPage);
    };

    function getResultsPage(pageNumber) {
      var data = $scope.params;
      data.pagesize = $scope.pagesize;
      data.page = (pageNumber - 1);
      $scope.pagination.current = pageNumber;
      Services.getItems('clients', data)
      .then(function( results ) {
        var pagingData = angular.fromJson(results.headers['x-pagination']);
        $scope.totalItems = pagingData.TotalCount;
        $scope.clients = results.data;
      });
    }
    getResultsPage(1);

    $scope.valid = function (client) {
      if ($scope.newPayment.Client.Id) {
        return !($scope.newPayment.Client.Id === client.Id);
      };
    };

    $scope.useThis = function (client) {
      $scope.newPayment.Client = client;
      $scope.newPayment.ReceivedFrom = client.Name;
      $scope.psClient = false;
    };

    $scope.removeClient = function () {
      $scope.newPayment.Client = {};
      $scope.newPayment.ReceivedFrom = "";
    }

    if ($scope.selectedInvoice.length > 0) {
      $scope.newPayment.TotalAmount = 0;
      angular.forEach($scope.selectedInvoice, function(value, key){
        $scope.newPayment.TotalAmount += value.TotalAmount;
      });
      if ($scope.selectedInvoice[0].PlacementTest) {
        $scope.newPayment.ReceivedFrom = $scope.selectedInvoice[0].PlacementTest.Student.SID + ' - ' + $scope.selectedInvoice[0].PlacementTest.Student.FullName;
      };
      if ($scope.selectedInvoice[0].Enrollment) {
        $scope.newPayment.ReceivedFrom = $scope.selectedInvoice[0].Enrollment.Student.SID + ' - ' + $scope.selectedInvoice[0].Enrollment.Student.FullName;
      };
      if ($scope.selectedInvoice[0].MakeUpTest) {
        $scope.newPayment.ReceivedFrom = $scope.selectedInvoice[0].MakeUpTest.Enrollment.Student.SID + ' - ' + $scope.selectedInvoice[0].MakeUpTest.Enrollment.Student.FullName;
      };
    } else {
      $state.go('^.list');
    }

    $scope.$watch('selectedInvoice', function(newValue, oldValue) {
      // $scope.newPayment.Change = 0;
      console.log(newValue);
      var totalDiscount = 0;
      angular.forEach(newValue, function(value, index){
        totalDiscount = totalDiscount + value.TotalDiscount;
      });
      $scope.newPayment.TotalDiscount = totalDiscount;
    }, true);

    $scope.postPayment = function(){
      $scope.newPayment.Invoices = [];
      if (!$scope.newPayment.Client.Id) {
        delete $scope.newPayment.Client;
      };
      angular.forEach($scope.selectedInvoice, function(value, key){
        $scope.newPayment.Invoices.push({Id: value.Id});
        // $scope.newPayment.TotalAmount += value.TotalAmount;
      });

      Services.add('payments', $scope.newPayment)
      .then(function(results){
        $scope.postedPayment = results.data;
        if ($scope.newPayment.PaymentStatus === 0) {
          $scope.openModal();
        } else {
          $state.go('^.list');
        }
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
    };

    // MODAL CONTROLLER
    var InvoiceModalCtrl = ['$scope', '$rootScope', '$modalInstance', 'Services', 'payment', '$filter', '_', function($scope, $rootScope, $modalInstance, Services, payment, $filter, _){

      // console.log(payment);

      $scope.invoiceList = function () {
        $state.go('^.list');
        $modalInstance.dismiss('cancel');
      };

      $scope.print = function () {
        $state.go('payments.show.print', { id:payment.Id });
        $modalInstance.dismiss('cancel');
      };

      $scope.payConfirm = function () {
        $state.go('payments.new', { id:payment.Id });
        $modalInstance.dismiss('cancel');
      };
    }];

    $scope.openModal = function (payment) {

      var modalInstance = $modal.open({
        templateUrl: 'invoiceConfirmation.html',
        controller: InvoiceModalCtrl,
        backdrop: 'static',
        keyboard: false,
        resolve: {
          payment: function () {
            return $scope.postedPayment;
          }
        }
      });
      modalInstance.result.then(function (selectedItem) {
        payment.discounts = selectedItem;
      }, function () {
        console.log('Modal dismissed at: ' + new Date());
      });
    };

    // PAGINATION
    // $scope.pagesize = 5;

    // $scope.Disc.pagination = {
    //   current: 1
    // };

    // $scope.pageChangedDisc = function(newPage) {
    //   getResultsPageDisc(newPage);
    // };

    // function getResultsPageDisc(pageNumber) {
    function getResultsPageDisc() {
      var data = $scope.Disc.params;
      // data.pagesize = 10;
      // data.page = (pageNumber - 1);
      // $scope.Disc.pagination.current = pageNumber;
      Services.getItems('student_discounts', data)
      .then(function( results ) {
        // var pagingData = angular.fromJson(results.headers['x-pagination']);
        // $scope.Disc.totalItems = pagingData.TotalCount;
        $scope.discounts = results.data;
      });
    };

    $scope.manageDiscount = function(invoice){
      $scope.psDiscounts = true;
      $scope.InvoiceChosen = invoice;
      // Services.getItem('invoices', invoice.Id, {'include': 'student,payment,student_discounts'})
      // .then(function(results){
      //   $scope.InvoiceChosen = results.data;
        if ($scope.InvoiceChosen.PlacementTest) {
          $scope.Disc.params.student = $scope.InvoiceChosen.PlacementTest.Student.Id;
          $scope.Disc.params.studentName = $scope.InvoiceChosen.PlacementTest.Student.FullName;
        };
        if ($scope.InvoiceChosen.Enrollment) {
          $scope.Disc.params.student = $scope.InvoiceChosen.Enrollment.Student.Id;
          $scope.Disc.params.studentName = $scope.InvoiceChosen.Enrollment.Student.FullName;
        };
        // getResultsPageDisc(1);
        getResultsPageDisc();
      // });
    };

    $scope.checkSelected = function(Id) {
      if ($scope.InvoiceChosen) {
        return _.where($scope.InvoiceChosen.StudentDiscounts, { Id: Id }).length > 0;
      };
    };

    $scope.toggleDiscount = function(discount) {
      console.log(discount);
      var items = _.where($scope.InvoiceChosen.StudentDiscounts, {Id: discount.Id});
      var item = _.findWhere($scope.InvoiceChosen.StudentDiscounts, {Id: discount.Id});

      if (items.length > 0) {
        $scope.InvoiceChosen.StudentDiscounts = _.without($scope.InvoiceChosen.StudentDiscounts, item);
      } else {
        $scope.InvoiceChosen.StudentDiscounts.push(discount);
      }
    };

    $scope.submitDiscount = function(){
      var TotalDisc = 0;
      angular.forEach($scope.InvoiceChosen.StudentDiscounts, function(newValue, oldValue){
        if (!newValue.Percentage) {
          newValue.Percentage = 0;
        };
        if (!newValue.Amount) {
          newValue.Amount = 0;
        };
        var disc = Math.abs(($scope.InvoiceChosen.TotalAmount*(newValue.Percentage/100))+newValue.Amount);
        TotalDisc = TotalDisc + disc;
      });
      $scope.InvoiceChosen.TotalDiscount = TotalDisc;

      var data = angular.copy($scope.InvoiceChosen);

      delete data.Enrollment;
      delete data.PlacementTest;
      delete data.TotalDiscount;
      delete data.MakeUpTest;
      Services.update('invoices', data, data.Id)
      .then(function(results){
        $scope.InvoiceChosen.TotalDiscount = results.data.TotalDiscount;
        $scope.InvoiceChosen.StudentDiscounts = results.data.StudentDiscounts;
        $scope.psDiscounts = false;
      }, function (results) {
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      })
    };
  }])
  .controller('PaymentCtrl', ['$scope', '$state', '$stateParams', '$filter', '_', function ($scope, $state, $stateParams, $filter, _) {

    console.log(_);
    console.log($filter);
    console.log($scope);
  }]);